package com.ciwong.epaper.modules.pad.homeworkwidget.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants;
import com.ciwong.epaper.modules.pad.homeworkwidget.common.util.Serviceutil;
import com.ciwong.epaper.modules.pad.homeworkwidget.presenter.DataProvider;
import com.ciwong.epaper.modules.pad.homeworkwidget.presenter.HomeworkWidgetCheckState;
import com.ciwong.epaper.modules.pad.homeworkwidget.presenter.PersonalInfor;
import com.ciwong.epaper.modules.pad.homeworkwidget.presenter.ReceverPresenter;
import com.ciwong.epaper.modules.pad.homeworkwidget.widget.remoteviews.HomeworkRemoteViewsDecorator;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.utils.ToastUtil;

import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG;
import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG_HOMEWORK;
import static com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants.JUMP_2_ACTIVITY_FLAG_ME_FRAGEENT;


/**
 * date :2018/8/29
 * author: lzh
 * description:
 * version:2.10
 */
public class HomeworkWidgetProvider extends AppWidgetProvider {

    private static final String TAG = "HomeworkWidgetProvider";
    private final long DELAY_TIME_INTERACTIVE_TUTORIAL = 2000;//延时时间
    private final Handler handler = new Handler();

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (AppWidgetConstants.ACTION_WIDGET_LOGIN.equals(intent.getAction())) {//点击登录
            makeServiceActive(context);
            clickLogin(context, intent);
        } else if (AppWidgetConstants.ACTION_WIDGET_JOIN_CLASS.equals(intent.getAction())) {//点击加入班级
            makeServiceActive(context);
            clickJoinClass(context, intent);
        } else if (AppWidgetConstants.ACTION_REFRESH_CLICK.equals(intent.getAction())) {//点击刷新
            makeServiceActive(context);
            clickRefresh(context, intent);
        } else if (AppWidgetConstants.ACTION_REFRESH_ALL_CLICK.equals(intent.getAction())) {//刷新整个页面
            updateAll(context);
        } else if (AppWidgetConstants.ACTION_REFRESH_AUTO.equals(intent.getAction())) {//自动刷新
            makeServiceActive(context);
            autoRefresh(context, intent);
        } else if (AppWidgetConstants.ACTION_JUMP_LISTITEM.equals(intent.getAction())) {//点击跳转相应 作业条目
            makeServiceActive(context);
            jumpToListItem(context, intent);
        } else if (AppWidgetConstants.ACTION_JUMP_MEFRAGMENT.equals(intent.getAction())) {//点击跳转我的页面
            makeServiceActive(context);
            jumpToMeFragemnt(context, intent);
        }

        /**
         * HomeworkReceiver转移广播
         */

        else if (LoginToken.ACTION_LOGIN_SUCCESS.equals(intent.getAction())) {//接收到登陆成功(app内部)
            makeServiceActive(context);
            ReceverPresenter.getInstance().appLoginSuccess(context, intent);
        } else if (LoginToken.ACTION_BIND_PHONE_SUCCESS.equals(intent.getAction())) {//接收绑定数据成功（app内部）
            makeServiceActive(context);
            ReceverPresenter.getInstance().bindPhoneSuccess(context, intent);
        } else if (LoginToken.ACTION_EXIT_LOGIN.equals(intent.getAction())) {//接收到退出登录（app内部）
            makeServiceActive(context);
            ReceverPresenter.getInstance().logoutSuccess(context, intent);
        } else if (EpaperConstant.BROADCAST_CLASS_CHANGE.equals(intent.getAction())) {//接收到加入班级成功（操作加入班级时的广播）（app内部）
            makeServiceActive(context);
            ReceverPresenter.getInstance().joinInClassSuccess(context, intent);
        }


        // 接收刷新作业列表消息.去请求网络数据
        else if (EpaperConstant.BROADCAST_JPUSH_GET_CUSTOM_MSG.equals(intent.getAction())) {//收到极光消息（app内部）
            makeServiceActive(context);
            ReceverPresenter.getInstance().getNetHomeworklist(context);
        } else if (EpaperConstant.BROADCAST_JPUSH_GET_NOTICE_MSG.equals(intent.getAction())) {//收到极光消息（app内部）
            makeServiceActive(context);
            ReceverPresenter.getInstance().getNetHomeworklist(context);
        } else if (EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG.equals(intent.getAction())) {//作业状态改变消息（app内部）
            makeServiceActive(context);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ReceverPresenter.getInstance().getNetHomeworklist(context);
                }
            }, DELAY_TIME_INTERACTIVE_TUTORIAL);

        } else if (EpaperConstant.BROADCAST_HOME_WORK_STATUS_INTERACTIVE_TUTORIAL_FINASH.equals(intent.getAction())) {//作业状态改变消息（app内部）
            makeServiceActive(context);
            //专门为互动教程 延时请求处理
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ReceverPresenter.getInstance().getNetHomeworklist(context);
                }
            }, DELAY_TIME_INTERACTIVE_TUTORIAL);
        }

        //接收到 登陆或者加入班级后刷新UI
        else if (AppWidgetConstants.ACTION_HAS_JOINED_CLASS.equals(intent.getAction())) {//网络检测到已经加入班级
            ReceverPresenter.getInstance().hasJoinedInClassSuccess(context, intent);
        } else if (AppWidgetConstants.ACTION_HAS_LOGIN_SUCESS.equals(intent.getAction())) {//接收到登陆成功widget
            ReceverPresenter.getInstance().widgetLoginSuccess(context, intent);
        }
        //请求数据后（网络或者本地数据）刷新UI
        else if (AppWidgetConstants.ACTION_LOAD_LOCAL_HOMEWORK_SUCCESS.equals(intent.getAction())) {//获取本地作业成功
            ReceverPresenter.getInstance().refreshListData(context, intent);
        } else if (AppWidgetConstants.ACTION_LOAD_NET_HOMEWORK_SUCCESS.equals(intent.getAction())) {//获取网络作业成功
            ReceverPresenter.getInstance().refreshListData(context, intent);
        } else if (AppWidgetConstants.ACTION_LOAD_NET_HOMEWORK_FAILED.equals(intent.getAction())) {//获取网络作业失败
            ReceverPresenter.getInstance().refreshListData(context, intent);
        } else {
            CWLog.e(TAG, "lzh 未知广播：HomeworkWidgetProvider   " + intent.getAction());
        }
        super.onReceive(context, intent);
    }

    /**
     * 确保服务运行
     *
     * @param context
     */
    private void makeServiceActive(Context context) {
        if (!Serviceutil.isServiceRunning(context, AppWidgetConstants.serviceName)) {
            CWLog.e(TAG, "lzh HomeworkWidgetProvider isServiceRunning 停止了 ");
            context.startService(new Intent(context, HomeworkwidgetmService.class));
        } else {
            CWLog.e(TAG, "lzh HomeworkWidgetProvider isServiceRunning 运行中 ");
        }
    }
    /**
     * 确保登录信息正常(如果没有登录信息 就重新刷新页面)
     *
     */
    private boolean checkHasLoginIfor(Context context) {
        if ( EApplication.getInstance()==null|| EApplication.getInstance().getUserInfoBase()==null){
            HomeworkRemoteViewsDecorator.getInstance().refreshAllView(context);
            return false;
        }
        return  true;
    }

    private void jumpToMeFragemnt(Context context, Intent intent) {
        if (!checkHasLoginIfor(context))return;
        Intent newIntent = new Intent(context, MainActivity.class);
        newIntent.putExtra(JUMP_2_ACTIVITY_FLAG, JUMP_2_ACTIVITY_FLAG_ME_FRAGEENT);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(newIntent);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        updateAll(context);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
    }

    @Override
    public void onDisabled(Context context) {
        context.stopService(new Intent(context, HomeworkwidgetmService.class));
        super.onDisabled(context);
    }

    private void updateAll(Context context) {
        if (!checkHasLoginIfor(context))return;
        Log.d(TAG, "lzh updateAll()");
        context.startService(new Intent(context, HomeworkwidgetmService.class));
    }

    ;

    /**
     * 收到点击事件 去登录
     *
     * @param context
     * @param intent
     */
    private void clickLogin(Context context, Intent intent) {
        if (HomeworkWidgetCheckState.isLogin(context)) {
            boolean flagIsBindPhone = false;
            Intent intentLogin = new Intent(AppWidgetConstants.ACTION_HAS_LOGIN_SUCESS);
            if (HomeworkWidgetCheckState.isBindPhone()) {
                flagIsBindPhone = true;
            }
            intentLogin.putExtra(AppWidgetConstants.FLAG_WIDGET_BIND_PHONE, flagIsBindPhone);
            context.sendBroadcast(intentLogin);
        } else {
            LoginToken.goToUnifiedLogin2(context);
        }
    }

    /**
     * 收到点击事件 去加入班级
     *
     * @param context
     * @param intent
     */
    private void clickJoinClass(Context context, Intent intent) {
        if (!checkHasLoginIfor(context))return;
        if (HomeworkWidgetCheckState.isJoinClass()) {
            context.sendBroadcast(new Intent(AppWidgetConstants.ACTION_HAS_JOINED_CLASS));
            return;
        } else HomeworkWidgetCheckState.clickCheckNetIsJoinClass(context);
    }

    /**
     * 收到点击事件 去刷新
     *
     * @param context
     * @param intent
     */
    private void clickRefresh(Context context, Intent intent) {
        if (!checkHasLoginIfor(context))return;
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return;
        }
        //点击刷新个人信息
        PersonalInfor.getInstance(context).refreshPerInfor(HomeworkWidgetCheckState.isLogin(context), HomeworkWidgetCheckState.isBindPhone());
        HomeworkRemoteViewsDecorator.getInstance().loading(context);
        autoRefresh(context, intent);
    }

    /**
     * 收到自动刷新广播 去刷新
     *
     * @param context
     * @param intent
     */
    private void autoRefresh(Context context, Intent intent) {
        if (!checkHasLoginIfor(context))return;
        DataProvider.getMyWorkList(context);
    }

    /**
     * 跳转作业列表
     *
     * @param context
     * @param intent
     */
    private void jumpToListItem(Context context, Intent intent) {
        if (!checkHasLoginIfor(context))return;
        Bundle extras = intent.getExtras();
        if (extras == null) {
            return;
        }
        Intent newIntent = new Intent(context, MainActivity.class);
        newIntent.putExtras(extras);
        newIntent.putExtra(JUMP_2_ACTIVITY_FLAG, JUMP_2_ACTIVITY_FLAG_HOMEWORK);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(newIntent);
    }
}
